<?php


namespace App\Http\Controllers\Admin;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;

class RoleController extends CommonController
{
    private static $ROLE_TABLE='role';
    private static $PERMISSION_TABLE='permission';
    private static $PERMISSION_ROLE_TABLE='permission_role';
    private static $USER='user';
    private static $USER_ROLE='user_role';

    public function addRole(Request $request){
        $res=$request->all();
        DB::beginTransaction();
        $form=json_decode($res['res'],true);
        $roles=[
            'name' => 'required|max:10',
            'info' => 'required|max:20',
        ];
        $messages = [
            'name.required' => '角色名称不能为空',
            'name.max' => '角色名称最长十个字符',
            'info.required' => '简介不能为空',
            'info.max' => '简介最长二十个字符',
        ];
        $validator =Validator::make($form,$roles,$messages);
        if ($validator->fails()) {
            return $this->ReturnJson(-1,$validator->errors()->first(),'');
        }
        $is_exit=DB::table(self::$ROLE_TABLE)
            ->where('delete_flag','=',0)
            ->where('name','=',$form['name'])
            ->exists();
        if ($is_exit){
            return $this->ReturnJson(-1,'角色名称重复','');
        }

        if (!isset($form['pid'])||empty($form['pid'])) {
            $pid = 0;
        }else{
            $pid=$form['pid'];
        }

        //处理选择权限
        $trees=[];
        foreach ($res['tree'] as $k=>$v){
            $v=json_decode($v,true);
            $trees[]=$v['id'];
            $trees[]=$v['pid'];
            $pid_see=DB::table(self::$PERMISSION_TABLE)
                ->where('id','=',$v['pid'])
                ->where('delete_flag','=',0)
                ->where('status','=',0)
                ->value('pid');
            if ($pid_see!=0){
                $trees[]=$pid_see;
            }
        }
        //去重
       $trees=array_unique($trees);
        try {
            $insert_data=[
                'name'=>$form['name'],
                'info'=>$form['info'],
                'pid'=>$pid,
                'created_by'=>$this->getUserId($request->header('token')),
                'created_time'=>date('Y-m-d H:i:s',time())
            ];
            $role_id=DB::table(self::$ROLE_TABLE)->insertGetId($insert_data);
            foreach ($trees as $k=>$val){
                if ($val!=0){
                    DB::table(self::$PERMISSION_ROLE_TABLE)->insert(['role_id'=>$role_id,'permission_id'=>$val,'created_by'=>$this->getUserId($request->header('token')),'created_time'=>date('Y-m-d H:i:s',time())]);
                }
            }
            DB::commit();
            return $this->ReturnJson(200,'添加成功','');
        }catch (\Exception $e){
            DB::rollBack();
            return $this->ReturnJson(-1,'添加失败'.$e->getMessage(),'');
        }
    }

    public function GetRoleList(Request $request){
        $page=$request->get('page')?$request->get('page'):self::$Page;
        $limit=$request->get('limit')?$request->get('limit'):self::$Limit;
        $res=DB::table('role as a')
            ->where(function ($query)use ($request){
                $query->where('a.delete_flag','=',0);
                if ($request->get('val')!=null||!empty($request->get('val'))){
                    $query->where('a.name','like','%'.$request->get('val').'%');
                }
            })
            ->select('a.id','a.name','a.info','a.status','a.pid')
            ->selectRaw('(select b.name from role as b where b.delete_flag = 0 and b.status= 0 and b.id = a.pid) as p_name')
            ->paginate($limit,'','',$page)
            ->toArray();
        return $this->ReturnJson(200,'success',$res);
    }

    public function CheckRoleStatus(Request $request){
        $res=$request->all();
        if (!isset($res['status'])||!isset($res['id'])){
            return $this->ReturnJson(-1,'参数错误','');
        }
        $status=$request->get('status')==1?1:0;
        try {
            DB::table(self::$ROLE_TABLE)->where('id','=',$res['id'])->update(['status'=>$status,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            return $this->ReturnJson(200,'修改成功','');
        }catch (\Exception $e){
            return $this->ReturnJson(-1,'error'.$e->getMessage(),'');
        }
    }

    public function GetRoleOption(){
        $res=DB::table(self::$ROLE_TABLE)
            ->where('delete_flag','=','0')
            ->where('status','=','0')
            ->select('id','name')
            ->get()
            ->toArray();
        return $this->ReturnJson(200,'success',$res);
    }

    public function GetCheckedTree(Request $request){
        $res=DB::table('role as a')
            ->leftJoin('permission_role as b','a.id','=','b.role_id')
            ->leftJoin('permission as c','c.id','=','b.permission_id')
            ->where('a.delete_flag','=','0')
            ->where('a.status','=','0')
            ->where('b.delete_flag','=','0')
            ->where('b.status','=','0')
            ->where('c.delete_flag','=','0')
            ->where('c.status','=','0')
            ->where('a.id','=',$request->get('role_id'))
            ->select('c.id')
            ->get()
            ->toArray();
        return $this->ReturnJson(200,'success',$res);
    }
    public function updateRole(Request $request){
        $res=$request->all();
        $form=json_decode($res['res'],true);
        $roles=[
            'name' => 'required|max:10',
            'info' => 'required|max:20',
        ];
        $messages = [
            'name.required' => '角色名称不能为空',
            'name.max' => '角色名称最长十个字符',
            'info.required' => '简介不能为空',
            'info.max' => '简介最长二十个字符',
        ];
        $validator =Validator::make($form,$roles,$messages);
        if ($validator->fails()) {
            return $this->ReturnJson(-1,$validator->errors()->first(),'');
        }

        $is_exit_role=DB::table(self::$ROLE_TABLE)
            ->where('delete_flag','=',0)
            ->where('name','=',$form['name'])
            ->where('id','<>',$form['id'])
            ->exists();
        if ($is_exit_role){
            return $this->ReturnJson(-1,'角色名称重复','');
        }

        if (!isset($form['pid'])||empty($form['pid'])) {
            $pid = 0;
        }else{
            $pid=$form['pid'];
        }

        //处理选择权限
        if (!isset($res['tree'])||empty($res['tree'])){
            //当不选权限时
            return $this->ReturnJson(-1,'不能滞空权限～','');
        }
        $trees=[];
        foreach ($res['tree'] as $k=>$v){
            $v=json_decode($v,true);
            $trees[]=$v['id'];
            $trees[]=$v['pid'];
            $pid_see=DB::table(self::$PERMISSION_TABLE)
                ->where('id','=',$v['pid'])
                ->where('delete_flag','=',0)
                ->where('status','=',0)
                ->value('pid');
            if ($pid_see!=0){
                $trees[]=$pid_see;
            }
        }
        //去重
        $trees=array_unique($trees);   //最新待写入权限
        try {
            DB::beginTransaction();
            $update_data=[
                'name'=>$form['name'],
                'info'=>$form['info'],
                'pid'=>$pid,
                'update_by'=>$this->getUserId($request->header('token')),
                'update_time'=>date('Y-m-d H:i:s',time())
            ];
            //更新角色表
            DB::table(self::$ROLE_TABLE)->where('id','=',$form['id'])->update($update_data);
            //处理角色权限关系
            DB::table(self::$PERMISSION_ROLE_TABLE)->where('role_id','=',$form['id'])->update(['status'=>1,'delete_flag'=>1,'update_time'=>date('Y-m-d H:i:s',time()),'update_by'=>$this->getUserId($request->header('token'))]);
            foreach ($trees as $k=>$val){
                if ($val!=0){
                    //查询数据库是否有记录 有记录直接更新
                    $is_exit=DB::table(self::$PERMISSION_ROLE_TABLE)
                        ->where('permission_id','=',$val)
                        ->where('role_id','=',$form['id'])
                        ->exists();
                    if ($is_exit){
                        DB::table(self::$PERMISSION_ROLE_TABLE)
                            ->where('permission_id','=',$val)
                            ->where('role_id','=',$form['id'])
                            ->update(['status'=>0,'delete_flag'=>0,'update_time'=>date('Y-m-d H:i:s',time()),'update_by'=>$this->getUserId($request->header('token'))]);
                    }else{
                        DB::table(self::$PERMISSION_ROLE_TABLE)->insert(['role_id'=>$form['id'],'permission_id'=>$val,'created_by'=>$this->getUserId($request->header('token')),'created_time'=>date('Y-m-d H:i:s',time())]);
                    }
                }
            }
            DB::commit();
            return $this->ReturnJson(200,'修改成功','');
        }catch (\Exception $e){
            DB::rollback();
            return $this->ReturnJson(-1,'修改失败'.$e->getMessage(),'');
        }

    }

    public function DelRole(Request $request){
        $res=$request->all();
        if (!isset($res['role_id'])||empty($res['role_id'])){
            return $this->ReturnJson(-1,'参数错误','');
        }
        //先查询是否有账户是在使用此角色
        $is_exists=DB::table('role as a')
            ->leftJoin('user_role as b','a.id','=','b.role_id')
            ->leftJoin('user as c','c.id','=','b.user_id')
            ->where('a.delete_flag','=',0)
            ->where('b.delete_flag','=',0)
            ->where('c.delete_flag','=',0)
            ->where('a.id','=',$res['role_id'])
            ->exists();
        if ($is_exists){
            return $this->ReturnJson(-1,'请先删除正在使用此角色的账号','');
        }
        try {
            DB::beginTransaction();
            DB::table(self::$ROLE_TABLE)->where('id','=',$res['role_id'])->update(['delete_flag'=>1,'status'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            DB::table(self::$ROLE_TABLE)->where('pid','=',$res['role_id'])->update(['delete_flag'=>1,'status'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            //处理角色权限关系表
            DB::table(self::$PERMISSION_ROLE_TABLE)->where('role_id','=',$res['role_id'])->update(['delete_flag'=>1,'status'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            $role_child_list=DB::table(self::$ROLE_TABLE)->where('pid','=',$res['role_id'])->select('id')->get()->toArray();
            foreach ($role_child_list as $k=>$v){
                DB::table(self::$PERMISSION_ROLE_TABLE)->where('role_id','=',$v->id)->update(['delete_flag'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            }
            DB::commit();
            return $this->ReturnJson(200,'删除成功','');
        }catch (\Exception $e){
            DB::rollBack();
            return $this->ReturnJson(-1,'error'.$e->getMessage(),'');
        }

    }

    public function GetRoleAll(){
        $res=DB::table(self::$ROLE_TABLE)
            ->where('delete_flag','=',0)
            ->where('status','=',0)
            ->select('id','name')
            ->get()
            ->toArray();
        return $this->ReturnJson(200,'success',$res);
    }

}
